package com.kc.saf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kc.saf.domain.CaseClassic;
import com.kc.saf.domain.CoreType;
import com.kc.saf.domain.SafetyAlertType;
import com.kc.saf.service.CaseClassicService;
import com.kc.saf.service.CoreTypeService;
import com.kc.saf.service.SafetyAlertTypeService;
import com.kc.saf.vo.CaseClassicVo;
import com.kc.saf.vo.WebPageVo;
import com.kc.sys.common.AppFileUtils;
import com.kc.sys.common.DataGridView;
import com.kc.sys.common.R;
import com.kc.sys.domain.User;
import com.kc.sys.util.UUIDUtil;
import com.kc.sys.util.WebUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 老杜
 * @since 2019-11-12
 */
@RestController
@RequestMapping("/caseClassic")
public class CaseClassicController {
    public final static String UPLOAD_FILE_PATH = "D:\\uploadFile\\";
    @Autowired
    private CaseClassicService caseClassicService;
    @Autowired
    private SafetyAlertTypeService safetyAlertTypeService;
    @Autowired
    private CoreTypeService coreTypeService;

    /**
     * 查询
     */
    @RequestMapping("loadAllCaseClassic")
    public DataGridView loadAllCaseClassic(CaseClassicVo caseClassicVo){
        //获取用户session
        //User user = (User)WebUtils.getSession().getAttribute("user");
        IPage<CaseClassic> page = new Page<>(caseClassicVo.getPage(),caseClassicVo.getLimit());
        QueryWrapper<CaseClassic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(caseClassicVo.getSafetyId()!=null&&caseClassicVo.getSafetyId()!=0,"safety_id",caseClassicVo.getSafetyId());
        queryWrapper.eq(caseClassicVo.getFileType()!=null&&caseClassicVo.getFileType()!=0,"file_type",caseClassicVo.getFileType());
        queryWrapper.like(StringUtils.isNotBlank(caseClassicVo.getClassicTitle()),"classic_title",caseClassicVo.getClassicTitle());
        queryWrapper.orderByDesc("ordernum").orderByDesc("create_date");
        caseClassicService.page(page,queryWrapper);
        List<CaseClassic> caseClassics = page.getRecords();
        for (CaseClassic caseClassic : caseClassics) {
            SafetyAlertType safetyAlertType = safetyAlertTypeService.getById(caseClassic.getSafetyId());
            CoreType coreType = coreTypeService.getById(caseClassic.getCoreId());
            if(null!=safetyAlertType){
                caseClassic.setSafetyName(safetyAlertType.getTypename());
            }
            if(null!=coreType){
                caseClassic.setCoreType(coreType.getTypename());
            }
        }
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    //根据Id查询五大核心
    @RequestMapping("loadCaseClassicById/{id}")
    public R loadCaseClassicById(@PathVariable("id") Integer id){
        try {
            CaseClassic caseClassic = caseClassicService.getById(id);
            return R.ok().data("item",caseClassic);
        }catch (Exception e){
            e.printStackTrace();
            return R.error().message("没有数据");
        }
    }
    /**
     * 递归获取某路径下的所有文件，文件夹，并输出
     */

    public static List<String> getFiles(String path) {
        List<String> strings = new ArrayList<>();
        File file = new File(path);
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
            // 获取路径下的所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 如果还是文件夹 递归获取里面的文件 文件夹
                if (files[i].isDirectory()) {
                    getFiles(files[i].getPath());
                } else {
                   String fileName = files[i].getPath().substring(files[i].getPath().lastIndexOf("\\")+1);
                   strings.add(fileName);
                }
            }
        } else {
        }
        return  strings;
    }
    @RequestMapping("addCaseClassic")
    public R addCaseClassic(CaseClassicVo caseClassicVo){
        try {
            User user = (User)WebUtils.getSession().getAttribute("user");
            caseClassicVo.setAuthor(user.getName());
            caseClassicVo.setCreateDate(new Date());
            if(caseClassicVo.getCaseImage()!=null&&caseClassicVo.getCaseImage().endsWith("_temp")) {
                String newName = AppFileUtils.renameFile(caseClassicVo.getCaseImage());
                caseClassicVo.setCaseImage(newName);
            }
            caseClassicService.save(caseClassicVo);
            return R.ok().message("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("添加失败");
        }
    }

    //更新4大核心详情
    @RequestMapping("updateCaseClassic")
    public R updateCaseClassic(CaseClassicVo caseClassicVo){
        try {
            if(caseClassicVo.getCaseImage()!=null&&caseClassicVo.getCaseImage().endsWith("_temp")) {
                String newName = AppFileUtils.renameFile(caseClassicVo.getCaseImage());
                caseClassicVo.setCaseImage(newName);
            }
            caseClassicService.updateById(caseClassicVo);
            return R.ok().message("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }
    /**
     * 根据Id 删除
     * */
    @RequestMapping("deleteCaseClassic")
    public R deleteById(Integer id){
        try {
            caseClassicService.removeById(id);
            return R.ok().message("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }


    //根据安全警示类型查询
    @RequestMapping("loadCaseClassicByType/{type}")
    public R loadCaseClassicByType(@PathVariable("type") Integer type){
        QueryWrapper<CaseClassic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("safety_id",type);
        queryWrapper.eq("available",1);
        List<CaseClassic> list = caseClassicService.list(queryWrapper);
        return  R.ok().data("item",list);
    }

    //加载最大的排序码
    @RequestMapping("loadCaseClassicMaxOrderNum")
    public Map<String ,Object> loadCaseClassicMaxOrderNum(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<CaseClassic> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<CaseClassic> list = caseClassicService.list(queryWrapper);
        if(list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else{
            map.put("value",1);
        }
        return map;
    }

    @RequestMapping("/uploadFileasdasdas")
    public WebPageVo uploadFile(@RequestParam("file") MultipartFile file){
        WebPageVo webPageVo = new WebPageVo();
        String fileName = null;
        String fileNowName = null;
        Boolean flag=false;
        Map<String,Object> param=new HashMap<>();
        if(file.isEmpty()){
            webPageVo.setMsg("文件不能为空");
            webPageVo.setCode(1);
            return webPageVo;
        }
        try{
            String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath();//获取当前资源的虚拟路径
            path1=path1+"upload/";
           // String  path1= UPLOAD_FILE_PATH;
            //创建一个文件夹
            Date date = new Date();
            //文件夹的名称
            String paths=path1+new SimpleDateFormat("yyyyMMdd").format(date);
            //如果不存在,创建文件夹
            File f = new File(paths);
            if(!f.exists()){
                f.mkdirs();
                //如果文件夹不存在创建一个
                fileName = file.getOriginalFilename();//获取原名称
                fileNowName = UUIDUtil.getUUID2()+"."+ FilenameUtils.getExtension(fileName);//生成唯一的名字
                File dest = new File(paths+"/"+fileNowName);
                file.transferTo(dest);
            }else{
                fileName = file.getOriginalFilename();//获取原名称
                fileNowName = UUIDUtil.getUUID2()+"."+ FilenameUtils.getExtension(fileName);//生成唯一的名字
                File dest = new File(paths+"/"+fileNowName);
                file.transferTo(dest);
            }

            webPageVo.setMsg(fileNowName);
            webPageVo.setCode(0);
        }catch(Exception e){
            e.printStackTrace();
            webPageVo.setMsg("上传失败,请重新上传");
            webPageVo.setCode(1);
        }
        return webPageVo;
    }

}

